package com.zjw.project.weixin.api.accessToken;

import com.zjw.project.weixin.main.MenuManager;
import com.zjw.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AccessTokenRedis {

    private static String ACCESS_TOKEN_KEY = "accesstoken:key";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "redisTemplate")
    ValueOperations<String, String> opsForValue;

    public String getAccessTokenVal() {
        if (redisTemplate.hasKey(ACCESS_TOKEN_KEY)) {
            return opsForValue.get(ACCESS_TOKEN_KEY);
        } else {
            String val = this.sendHttpAccessTokenVal();
            opsForValue.set(ACCESS_TOKEN_KEY, val);
            redisTemplate.expire(ACCESS_TOKEN_KEY, 2, TimeUnit.HOURS);
            return val;
        }
    }

    /*
     https请求方式: GET
     */
    private static String TOKEN_GET_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /*
     微信服务器获取生成accessToken方法
     */
    private String sendHttpAccessTokenVal() {
        String url = TOKEN_GET_URL.replace("APPID", MenuManager.appId).replace("APPSECRET", MenuManager.appSecret);
        try {
            JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
            String accessToken = jsonObject.getString("access_token");
            log.info("accessToken的值获取成功：" + accessToken);
            return accessToken;
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return  null;
    }
}